<template>
  <div class="cur-phase-chart">
    <div class="chart-legend">
      <PhaseLegend :crossStatusData="tscControlData"
            :phaseList="phaseList"
            showDataType="phase"
            :noClick="true"
            :isShowCurrentStage="false"
            StageWidth="46px"
            StageHeight="52px"
            dirWidth="46px"
            dirHeight="52px"
            dirWidths="46px"
            dirHeights="52px"
            :showStyle="{top:'2PX',left:'9px'}"
            :showStyles="{top:'0PX',left:'7px'}"
            ></PhaseLegend>
    </div>

    <div ref="curPhaseGanttChart" class="chart2"></div>
  </div>
</template>

<script>
import * as echart from 'echarts'
import { getTscControl } from '../../../../api/control.js'
import { getMessageByCode } from '../../../../utils/responseMessage'

import { getTheme } from '../../../../utils/auth.js'

var DIM_CATEGORY_INDEX = 0
var DIM_TIME_ARRIVAL = 1
var DIM_TIME_DEPARTURE = 2
var DIM_PHASEID = 3
// let gantHeightRatio = 0.5
// let redlineHeightRatio = 0.1

export default {
  data () {
    return {
      filterTags: [],
      rawData: {
        flight: {
          dimensions: ['Index',
            this.$t('openatc.patternstatistic.starttime'),
            this.$t('openatc.patternstatistic.endtime'),
            this.$t('openatc.patternstatistic.phaseid')],
          data: [
            [0, '2024-05-13 13:15:56.788', '2024-05-13 13:34:13.488', 1],
            [1, '2024-05-13 13:29:10.641', '2024-05-13 13:41:45.117', 2],
            [0, '2024-05-13 13:40:07.335', '2024-05-13 13:41:34.597', 1],
            [2, '2024-05-13 13:38:07.335', '2024-05-13 13:44:34.597', 3]
          ]
        },
        parkingApron: {
          data: [
            ['相位1'],
            ['相位2'],
            ['相位5']
          ],
          dimensions: ['Name']
        }
      },
      tscControlData: {},
      PatternData: [],
      mock: [{
        time: '2024-09-06 12:05:46.503',
        data: {
          current_phase: [9, 10]
        }
      }, {
        time: '2024-09-06 12:10:53.445',
        data: {
          current_phase: [9, 10]
        }
      }, {
        time: '2024-09-06 12:05:46.503',
        data: {
          current_phase: [11, 12]
        }
      }, {
        time: '2024-09-06 12:10:53.445',
        data: {
          current_phase: [11, 12]
        }
      }, {
        time: '2024-09-06 12:05:46.503',
        data: {
          current_phase: [13, 14]
        }
      }, {
        time: '2024-09-06 12:10:53.445',
        data: {
          current_phase: [13, 14]
        }
      }, {
        time: '2024-09-06 12:05:46.503',
        data: {
          current_phase: [15, 16]
        }
      }, {
        time: '2024-09-06 12:10:53.445',
        data: {
          current_phase: [15, 16]
        }
      }, {
        time: '2024-09-06 12:05:46.503',
        data: {
          current_phase: [17, 18]
        }
      }, {
        time: '2024-09-06 12:10:53.445',
        data: {
          current_phase: [17, 18]
        }
      }]
    }
  },
  props: {
    RealtimeHistoryPatternData: {
      type: Object
    },
    date: {
      type: Array
    },
    ASCID: undefined,
    phaseList: {
      type: Array
    }
  },
  watch: {
    RealtimeHistoryPatternData: function (val) {
      this.PatternData = val.data.data
      this.filerTimingData = this.getCurphaseData()
      console.log('filerTimingData', this.filerTimingData)
      this.createGantData()
      this.createYLabelData()
      this.startDate = this.date[0]
      this.endDate = this.date[1]
      this.initChart()
    }
  },
  mounted () {
    // this.initChart()
    this.getTscControlData()
  },
  methods: {
    getCurphaseData () {
      let result = []
      // this.PatternData = this.PatternData.concat(this.mock)
      this.PatternData.forEach((data, index) => {
        let curpahses = data.data.current_phase
        if (curpahses) {
          curpahses.forEach(phase => {
            let obj = {
              ...data,
              phaseid: phase,
              beginTime: data.time
            }
            if (this.PatternData[index + 1]) {
              obj.endTime = this.PatternData[index + 1].time
            }
            result.push(obj)
          })
        }
      })
      return result
    },
    createGantData () {
      let phaseData = []
      let phaseidsArr = []
      let IndexArr = []
      let gantIndexArr = [] // 甘特图要求index是连续的，不然会不显示
      this.filerTimingData.forEach((ele, index) => {
        let phaseid = ele.phaseid
        IndexArr.push(phaseid)
      })
      gantIndexArr = Array.from(new Set(IndexArr)).sort((a, b) => a - b)

      this.filerTimingData.forEach((ele, index) => {
        let phase = []

        phase[1] = ele.beginTime
        let phaseId = ele.phaseid
        phase[3] = phaseId
        phase[0] = gantIndexArr.indexOf(phaseId)
        if (ele.endTime) {
          phase[2] = ele.endTime
        }
        phaseData.push(phase)
        phaseidsArr.push(ele.phaseid)
      })
      console.log('phaseData', phaseData)
      this.rawData.flight.data = phaseData
      this.phaseidsArr = Array.from(new Set(phaseidsArr)).sort((a, b) => a - b)
      // console.log(this.phaseidsArr)
    },
    createYLabelData () {
      let ylabeldata = this.phaseidsArr.map(phaseid => {
        return [phaseid]
      })
      this.ylabeldata = ylabeldata
      this.rawData.parkingApron.data = ylabeldata
    },
    initChart () {
      const chartDom = this.$refs.curPhaseGanttChart
      const myChart = echart.init(chartDom)
      window.addEventListener('resize', function () {
        myChart.resize()
      })

      const option = {
        tooltip: {},
        animation: false,
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: 0,
            filterMode: 'weakFilter',
            height: 20,
            bottom: 20,
            start: 0,
            end: 10,
            handleIcon:
          'path://M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleSize: '100%',
            showDetail: false
          },
          {
            type: 'inside',
            id: 'insideX',
            xAxisIndex: 0,
            filterMode: 'weakFilter',
            start: 0,
            end: 10,
            zoomOnMouseWheel: false,
            moveOnMouseMove: true
          }
        ],
        grid: {
          show: true,
          containLabel: true,
          height: '89%',
          width: '90%',
          right: '60',
          left: '60',
          top: '20',
          bottom: '40',
          borderWidth: 0
        },
        xAxis: {
          type: 'time',
          splitLine: {
            lineStyle: {
              color: [getTheme() === 'light' ? '#DCDFE6' : '#30384d']
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          axisLabel: {
            color: getTheme() === 'light' ? '#666666' : '#B9BABF',
            inside: false,
            align: 'center'
          }
        },
        yAxis: {
          axisTick: { show: false },
          splitLine: { show: false },
          axisLine: { show: false },
          axisLabel: { show: false },
          min: 0,
          max: this.rawData.parkingApron.data.length
        },
        series: [
          {
            id: 'flightData',
            type: 'custom',
            renderItem: this.renderGanttItem,
            dimensions: this.rawData.flight.dimensions,
            encode: {
              x: [DIM_TIME_ARRIVAL, DIM_TIME_DEPARTURE],
              y: DIM_CATEGORY_INDEX,
              tooltip: [DIM_PHASEID, DIM_TIME_ARRIVAL, DIM_TIME_DEPARTURE]
            },
            tooltip: {
              borderColor: '#69b654',
              formatter: function (params) {
                let tooltipstr = ''
                // console.log(params)
                if (params) {
                  tooltipstr = `
                  <div class="timing-tooltip">
                    <div><span class="tooltiplabel">${params.dimensionNames[3]}:</span>${params.data[3]}</div>
                    <div><span class="tooltiplabel">${params.dimensionNames[1]}:</span>${params.data[1]}</div>
                    <div><span class="tooltiplabel">${params.dimensionNames[2]}:</span>${params.data[2]}</div>
                  </div>`
                }
                return tooltipstr
              }
            },
            data: this.rawData.flight.data
          },
          {
            type: 'custom',
            renderItem: this.renderAxisLabelItem,
            dimensions: this.rawData.parkingApron.dimensions,
            encode: {
              x: -1,
              y: 0
            },
            data: this.rawData.parkingApron.data.map(function (item, index) {
              return [index].concat(item)
            })
          },
          {
            type: 'custom',
            name: '红线',
            z: 1,
            tooltip: {
              show: false
            },
            renderItem: this.renderRedLine,
            dimensions: this.rawData.flight.dimensions,
            encode: {
              x: [DIM_TIME_ARRIVAL, DIM_TIME_DEPARTURE],
              y: DIM_CATEGORY_INDEX,
              tooltip: [DIM_CATEGORY_INDEX, DIM_TIME_ARRIVAL, DIM_TIME_DEPARTURE]
            },
            data: this.rawData.flight.data
          }
        ]
      }
      let yScroll = [{
        type: 'slider',
        yAxisIndex: 0,
        width: 20,
        right: 10,
        top: 20,
        bottom: 20,
        start: 20,
        end: 100,
        handleIcon:
          'path://M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
        handleSize: '100%',
        showDetail: false
      },
      {
        type: 'inside',
        id: 'insideY',
        yAxisIndex: 0,
        start: 20,
        end: 100,
        zoomOnMouseWheel: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true
      }]
      if (this.phaseidsArr.length > 8) {
        option.dataZoom = option.dataZoom.concat(yScroll)
      }
      myChart.setOption(option)
    },
    renderRedLine (params, api) {
      var categoryIndex = api.value(DIM_CATEGORY_INDEX)
      var timeArrival = api.coord([this.startDate, categoryIndex])
      var timeDeparture = api.coord([this.endDate, categoryIndex])
      var barLength = timeDeparture[0] - timeArrival[0]
      // var barHeight = api.size([0, 1])[1] * redlineHeightRatio
      // var gantHeight = api.size([0, 1])[1] * gantHeightRatio
      var barHeight = 4
      var gantHeight = 8
      var x = timeArrival[0]
      var y = timeArrival[1] - gantHeight / 2 - barHeight / 2

      var rectNormal = this.clipRectByRect(params, {
        x: x,
        y: y,
        width: barLength,
        height: barHeight
      })

      return {
        type: 'group',
        children: [
          {
            type: 'rect',
            shape: rectNormal,
            style: api.style({ fill: '#f27979' })
          }
        ]
      }
    },
    renderGanttItem (params, api) {
      var categoryIndex = api.value(DIM_CATEGORY_INDEX)
      var timeArrival = api.coord([api.value(DIM_TIME_ARRIVAL), categoryIndex])
      var timeDeparture = api.coord([api.value(DIM_TIME_DEPARTURE), categoryIndex])
      var barLength = timeDeparture[0] - timeArrival[0]
      // Get the heigth corresponds to length 1 on y axis.
      // var barHeight = api.size([0, 1])[1] * gantHeightRatio
      var barHeight = 8

      var x = timeArrival[0]
      var y = timeArrival[1] - barHeight

      var rectNormal = this.clipRectByRect(params, {
        x: x,
        y: y,
        width: barLength,
        height: barHeight
      })

      return {
        type: 'group',
        children: [
          {
            type: 'rect',
            shape: rectNormal,
            style: api.style({ fill: '#69b654' })
          }
        ]
      }
    },
    clipRectByRect (params, rect) {
      return echart.graphic.clipRectByRect(rect, {
        x: params.coordSys.x,
        y: params.coordSys.y,
        width: params.coordSys.width,
        height: params.coordSys.height
      })
    },
    renderAxisLabelItem (params, api) {
      var y = api.coord([0, api.value(0)])[1]
      if (y < params.coordSys.y + 5) {
        return
      }
      return {
        type: 'group',
        position: [10, y],
        children: [
          {
            type: 'text',
            style: {
              x: 24,
              y: -3,
              text: api.value(1),
              textVerticalAlign: 'bottom',
              textAlign: 'center',
              textFill: getTheme() === 'light' ? '#666666' : '#B9BABF'
            }
          }
        ]
      }
    },
    getTscControlData () {
      this.tscControlData = {}
      getTscControl(this.ASCID).then((data) => {
        if (!data.data.success) {
          let agentid = data.data.data.agentid
          let commomMsg = this.$t('openatc.greenwaveoptimize.device') + agentid
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
            }
          } else {
            this.$message.error(parrenterror + ',' + commomMsg)
          }
        }
        this.tscControlData = data.data.data.data
      }).catch(error => {
        console.log(error)
      })
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  .cur-phase-chart {
    height: 100%;
  }
  .chart-legend {
    position: absolute;
    right: 0PX;
    top: 0PX;
    }
</style>
